import pymysql
from Config import Config

class RobotHistoryModel:
    def __init__(self,id=None,robot_no=None,robot_act=None,act_data=None,update_time=None ):
        self.id = id
        self.robot_no = robot_no
        self.robot_act = robot_act
        self.act_data = act_data
        self.update_time = update_time

    def save(self):
        config = Config()
        db_config =config.get_config()
        connection = pymysql.connect(**db_config)
        try:
            with connection.cursor() as cursor:
                if self.id == None:
                   sql = "INSERT INTO robot_history (robot_no,robot_act,act_data,updata_time) VALUES (%s,%s,%s,%s)"
                   cursor.execute(sql,(self.robot_no,self.robot_act,self.act_data,self.update_time))
                else:
                    sql = "UPDATE robot_history SET robot_no=%s,robot_act=%s,act_data=%s,updata_time=%s WHERE id=%s"
                    cursor.execute(sql,(self.robot_no,self.robot_act,self.act_data,self.update_time,self.id))
                connection.commit()
        finally:
            connection.close()
    @staticmethod #根据当前系统时间获取机器人动作数量合计
    def get_act_qty_by_now():
        config = Config()
        db_config = config.get_config()
        connection = pymysql.connect(**db_config)
        try:
            with connection.cursor() as cursor:
                sql ="SELECT count(robot_act)as act_qty ,robot_act FROM `robot_history` where DATE(update_time) = DATE(NOW()) GROUP BY robot_act ORDER BY robot_act"
                cursor.execute(sql)
                result = cursor.fetchall()
                return result
        finally:
            connection.close()
# SS=RobotHistoryModel.get_act_qty_by_now()
# print(SS)